<template>
  <div>
    <el-row>
      <el-col :xs="24" :md="12" :style="{height: '350px'}">
        <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            @realTime="realTime"
        />
      </el-col>
      <el-col :xs="24" :md="12" :style="{height: '350px'}">
        <span class="avatar-title">头像预览</span>
        <div class="avatar-upload-preview" :style="{'width':`${previews.w}px`,'height':`${previews.h}px`}">
            <img :src="previews.url" :style="previews.img" alt="头像"/>
        </div>
      </el-col>
    </el-row>
    <br/>
    <el-row>
      <el-col :lg="{span: 1, offset: 2}" :md="2">
        <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"/>
      </el-col>
      <el-col :lg="{span: 1, offset: 1}" :md="2">
        <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"/>
      </el-col>
      <el-col :lg="{span: 1, offset: 1}" :md="2">
        <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"/>
      </el-col>
      <el-col :lg="{span: 1, offset: 1}" :md="2">
        <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"/>
      </el-col>
      <el-col :lg="{span: 2, offset: 6}" :md="2">
        <el-button type="primary" size="small" @click="uploadImg()">上 传</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts">
import {Component, Emit, Prop, Ref, Vue} from 'vue-property-decorator';

@Component
export default class Cropper extends Vue {

  @Prop({
    default: () => ({
      img: '', //裁剪图片的地址
      autoCrop: true, // 是否默认生成截图框
      autoCropWidth: 200, // 默认生成截图框宽度
      autoCropHeight: 200, // 默认生成截图框高度
      fixedBox: true // 固定截图框大小 不允许改变
    })
  })
  private options!: any;

  @Prop({
    default: 'file'
  }) private formDataName!: string;

  @Ref('cropper') private cropper: any;


  private previews: any = {};

  // 向左旋转
  rotateLeft() {
    this.cropper.rotateLeft();
  }

  // 向右旋转
  rotateRight() {
    this.cropper.rotateRight();
  }

  // 图片缩放
  changeScale(num) {
    num = num || 1;
    this.cropper.changeScale(num);
  }

  // 上传图片
  uploadImg() {
    this.cropper.getCropBlob((data: any) => {
      const formData = new FormData();
      formData.append(this.formDataName, data);
      this.upload(formData);
      this.cropper.clearCrop();
    });
  }

  @Emit('upload')
  upload(res: any) {
    return res;
  }

  // 实时预览
  realTime(data: any) {
    this.previews = data;
  }

}
</script>

<style scoped lang="scss">
.avatar-title {
  display: block;
  text-align: center;
}

.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 180px;
  height: 180px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>

